<template>
  <div class="p-6">
    <div class="bg-white rounded-lg shadow-md p-6">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-semibold text-gray-800">我的资料</h2>
        <el-button type="primary" size="small" @click="handleSave" :loading="saving">
          保存修改
        </el-button>
      </div>

      <el-form
        ref="profileForm"
        :model="profileData"
        :rules="rules"
        label-position="top"
      >
        <!-- 头像上传 -->
        <div class="flex items-center mb-6">
          <el-avatar :size="100" :src="avatarUrl" class="border-4 border-gray-100">
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="ml-6">
            <el-upload
              class="avatar-uploader"
              action="#"
              :http-request="uploadAvatar"
              :show-file-list="false"
              accept="image/*"
            >
              <el-button type="primary" plain>更换头像</el-button>
            </el-upload>
            <p class="text-xs text-gray-500 mt-2">支持 JPG、PNG 格式，文件小于 2MB</p>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="mb-8">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="profileData.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileData.email" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="profileData.nickname" placeholder="请输入昵称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="profileData.phone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="个人简介" prop="bio">
            <el-input
              v-model="profileData.bio"
              type="textarea"
              :rows="3"
              placeholder="请输入个人简介"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 账号信息 -->
        <div class="border-t border-gray-200 pt-6">
          <h3 class="text-lg font-medium text-gray-700 mb-4">账号信息</h3>
          <div class="flex py-2 border-b border-gray-100">
            <span class="w-24 text-gray-500">注册时间</span>
            <span class="flex-1 text-gray-800">{{ formatDate(profileData.createdAt) }}</span>
          </div>
          <div class="flex py-2 border-b border-gray-100">
            <span class="w-24 text-gray-500">最后登录</span>
            <span class="flex-1 text-gray-800">{{ formatDate(profileData.lastLogin) }}</span>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { useUserStore } from '../store'
import { formRules } from '../utils/validate'
import { getAssetUrl } from '../utils/asset'

const userStore = useUserStore()

// 表单引用
const profileForm = ref(null)

// 状态
const saving = ref(false)

// 个人资料数据
const profileData = reactive({
  username: '',
  email: '',
  nickname: '',
  phone: '',
  bio: '',
  avatar: '',
  createdAt: '',
  lastLogin: ''
})

// 头像URL
const avatarUrl = computed(() => {
  return getAssetUrl(profileData.avatar || '/images/default-avatar.png')
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  loadUserProfile()
})

// 加载用户资料
async function loadUserProfile() {
  try {
    const userInfo = userStore.userInfo
    
    Object.assign(profileData, {
      username: userInfo.username || '',
      email: userInfo.email || '',
      nickname: userInfo.nickname || '',
      phone: userInfo.phone || '',
      bio: userInfo.bio || '',
      avatar: userInfo.avatar || '',
      createdAt: userInfo.createdAt || new Date().toISOString(),
      lastLogin: userInfo.lastLogin || new Date().toISOString()
    })
  } catch (error) {
    console.error('加载用户资料失败:', error)
    ElMessage.error('加载用户资料失败')
  }
}

// 上传头像
async function uploadAvatar(options) {
  try {
    const file = options.file
    
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('请上传图片文件')
      return
    }
    
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 2MB')
      return
    }
    
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      profileData.avatar = e.target.result
    }
    
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 保存个人资料
async function handleSave() {
  try {
    await profileForm.value.validate()
    saving.value = true
    await userStore.updateUserInfo({
      username: profileData.username,
      nickname: profileData.nickname,
      phone: profileData.phone,
      bio: profileData.bio,
      avatar: profileData.avatar
    })
    ElMessage.success('个人资料已更新')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '未知'
  
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}
</script>